package role

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"goAdminV1/api/role/v1"
	"goAdminV1/internal/model"
	"goAdminV1/utility"
	"time"
)

func (c *ControllerV1) RoleUpdate(ctx context.Context, req *v1.RoleUpdateReq) (res *v1.RoleUpdateRes, err error) {
	// 查询角色是否存在
	role, err := model.GetRoleById(ctx, req.Id)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}
	if role == nil {
		return nil, utility.Error(utility.CodeOperation, gerror.New("角色不存在"))
	}
	now := time.Now().Unix()

	// 更新角色基本信息
	updateData := map[string]interface{}{
		"role_name":   req.RoleName,
		"parent_id":   req.ParentId,
		"identify":    req.Identify,
		"description": req.Description,
		"data_range":  req.DataRange,
		"departments": req.Departments,
		"update_at":   now,
	}
	// 更新角色数据
	if err := model.UpdateRole(ctx, req.Id, updateData); err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	// 重新关联权限
	if err := model.DeleteRolePermissions(ctx, req.Id); err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}
	if len(req.Permissions) > 0 {
		if err := model.InsertRolePermissions(ctx, req.Id, req.Permissions); err != nil {
			return nil, utility.Error(utility.CodeOperation, err)
		}
	}

	// 返回成功响应
	return &v1.RoleUpdateRes{
		RoleId:  req.Id,
		Message: "角色更新成功",
	}, nil
}
